package com.sunwayhorizo.health.common.zipUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import com.sunwayhorizo.health.business.dto.clinic.orders.SubstanceAdmtDTO;
import com.sunwayhorizo.health.common.convertXMLFromObject.ParseObjectToXML;

public class SimpleGZip
{

    public static byte[] compress(byte[] data) throws IOException
    {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
        GZIPOutputStream gzos = new GZIPOutputStream(bos);

        byte[] buf = new byte[1024];
        int len;
        while ((len = bis.read(buf)) >= 0)
        {
            gzos.write(buf, 0, len);
        }
        bis.close();
        gzos.close();

        return bos.toByteArray();
    }

    public static byte[] compress(String data) throws IOException
    {
        return compress(data.getBytes());
    }

    /**
     * 
     * @param data          需要压缩的字符串
     * @param encode        字符集
     * @return
     * @throws IOException
     */
    public static byte[] compress(String data, String encode) throws IOException
    {
        return compress(data.getBytes(encode));
    }

    public static byte[] deCompress(byte[] data) throws IOException
    {
        ByteArrayInputStream bis = new ByteArrayInputStream(data);
        GZIPInputStream gzis = new GZIPInputStream(bis);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);

        byte[] buf = new byte[1024];
        int len;
        while ((len = gzis.read(buf)) >= 0)
        {
            bos.write(buf, 0, len);
        }
        gzis.close();
        bis.close();

        return bos.toByteArray();
    }

    public static String deCompressAsString(byte[] data) throws IOException
    {
        return new String(deCompress(data));
    }

    /**
     * 
     * @param data         需要解压缩的二进制
     * @param encode       字符集
     * @return
     * @throws IOException 
     */
    public static String deCompressAsString(byte[] data, String encode) throws IOException
    {
        return new String(deCompress(data), encode);
    }

    /**
     * 这是一个Demo，对字符串进行二进制压缩，并解压缩还原
     * 
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception
    {
        String originalStr = new ParseObjectToXML().converXmlFromObject(new SubstanceAdmtDTO());
        System.out.println("原文本占用空间:  " + originalStr.getBytes("UTF-8").length + "B");

        byte[] zipBin = SimpleGZip.compress(originalStr, "UTF-8");

        System.out.println("压缩后二进制占用空间:  " + zipBin.length + "B");

        String recoverStr = SimpleGZip.deCompressAsString(zipBin, "UTF-8");
        System.out.println(recoverStr.equals(originalStr));
    }
}
